// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.apps.moderator;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * An activity for the user to enter their own new submissions (questions).
 */
public class UserSubmissionActivity extends ModeratorActivity {

  private static final String TAG = UserSubmissionActivity.class.getName();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_submission);
    setHasContent(true); // Stops errors from closing the activity
    TextView heading = (TextView) findViewById(R.id.Heading);
    heading.setText(String.format(getString(R.string.post_a_new_submission),
        getIntent().getStringExtra("topicName")));
    Button button = (Button) findViewById(R.id.PostButton);
    button.setOnClickListener(new OnClickListener(){
      @Override
      public void onClick(View v) {
        if (ensureLogin()) {
          // Pull the IDs out of the extras
          int seriesId = getIntent().getIntExtra("seriesId", -1);
          int topicId = getIntent().getIntExtra("topicId", -1);
          String postString = ((EditText) findViewById(R.id.SubmissionText)).getText().toString();
          try {
            postJsonData(API_URL_BASE + "series/" + seriesId + "/topics/" + topicId +
                "/submissions", new JSONObject().
                put("data", new JSONObject().put("text", postString)));
            finish();
          } catch (AccessException e) {
            Log.e(TAG, "An error occurred", e);
            alert(R.string.cannot_submit);          
          } catch (JSONException e) {
            Log.e(TAG, "An error occurred", e);
            alert(R.string.cannot_submit);
          }
        }
      }});
  }
}
